package com.gack.business.dao;

import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.gack.business.vo.BusinessCardRecordItemVO;

/**
 * 
 * @author ws
 * 2018-6-15
 */
@Repository
public class BusinessCardRecordDao {

	@Autowired
	private EntityManager em;
	
	/**
	 * 根据公司id,查询某公司的购卡记录(已支付的记录)(若page和size都为-1,则为全部查找;否则为分页查找)  按购买日期降序排序
	 * @param page 请求第几页  从0开始   
	 * @param size 每页显示数量
	 * @param enterpriseId 公司id
	 * @return businessCardRecordItemList:购卡记录集合   total:全部购卡记录数量
	 */
	public Map<String, Object> findBusinessCardRecordItemVOByEnterpriseId(Integer page, Integer size, String enterpriseId){
		Map<String, Object> map = new HashMap<>();
		String jpql = "select bcr.id,"
				+ " case (select u.is_check"
						+ " from user u"
						+ " where u.id=bcr.uid)"
				+ " when 0 then (select u.nickname"
								+ " from user u"
								+ " where u.id=bcr.uid)"
				+ " when 1 then (select u.real_name"
								+ " from user u"
								+ " where u.id=bcr.uid)"
				+ " end as user_name_for_show,"
				+ " bcr.pay_amount,"
				+ " bcr.number,"
				+ " (select c.face_value from commodity c where c.id=bcr.cid) as face_value,"
				+ " bcr.create_time"
				+ " from businesscardrecord bcr"
				+ " where bcr.pay=1"
				+ " and bcr.eid=:enterpriseId"
				+ " order by bcr.create_time desc";
		
		Query query = em.createNativeQuery(jpql, BusinessCardRecordItemVO.class);
		query.setParameter("enterpriseId", enterpriseId);
		map.put("total", query.getResultList().size());
		
		if(page != -1 && size != -1){
			jpql += " limit " +  page*size + ", " +size;
		}
		Query query1 = em.createNativeQuery(jpql, BusinessCardRecordItemVO.class);
		query1.setParameter("enterpriseId", enterpriseId);
		map.put("businessCardRecordItemList", query1.getResultList());
		
		return map;
	}
	
}
